package com.djhu.newscollector.crawel.imp.holder;

import com.djhu.newscollector.core.job.BaseJob;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.JdkSerializationRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import redis.clients.jedis.JedisPoolConfig;

/**
 * Created by zw on 2018/2/11.
 */
public class RedisJobHolder extends BaseJobHolder{
    private static Logger logger = LogManager.getLogger(RedisJobHolder.class.getName());
    private String ip;
    private Integer port;
    private String auth;
    private RedisProperties redisProperties;

    private RedisTemplate redisTemplate;
    public RedisJobHolder() {
    }

    public RedisJobHolder(String ip, Integer port, String auth) {
        this.ip = ip;
        this.port = port;
        this.auth = auth;
        init();
        //redisProperties = new RedisProperties();
    }

    public void init() {
        redisProperties = new RedisProperties();
        redisProperties.setIp(ip);
        redisProperties.setAuth(auth);
        redisProperties.setPort(port);
        JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
        jedisPoolConfig.setMaxTotal(redisProperties.getMaxActive());
        jedisPoolConfig.setMaxIdle(redisProperties.getMaxIdle());
        jedisPoolConfig.setTestOnBorrow(redisProperties.getTestOnBorrow());

        JedisConnectionFactory jedisConnectionFactory = new JedisConnectionFactory();
        jedisConnectionFactory.setHostName(redisProperties.getIp());
        jedisConnectionFactory.setPassword(redisProperties.getAuth());
        jedisConnectionFactory.setPort(redisProperties.getPort());
        jedisConnectionFactory.setPoolConfig(jedisPoolConfig);
        jedisConnectionFactory.afterPropertiesSet();

        redisTemplate = new RedisTemplate();
        redisTemplate.setConnectionFactory(jedisConnectionFactory);
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        redisTemplate.setValueSerializer( new JdkSerializationRedisSerializer(this.getClass().getClassLoader()));
        redisTemplate.afterPropertiesSet();
        logger.info("redisTemplate init success!!!");
    }

    @Override
    public  synchronized boolean  contains(BaseJob job) {
        return redisTemplate.hasKey(job.id());
    }

    @Override
    public synchronized void remove(BaseJob job) {
        redisTemplate.delete(job.id());
    }

    @Override
    public synchronized void clear() {
        throw new RuntimeException("redis unsupport clear handle");
        //redisTemplate.
    }

    @Override
    public synchronized void add0(BaseJob job) {
        redisTemplate.opsForValue().set(job.id(),job.name());
    }
}